#include "mat_arrow.h"

#include "mat_define.h"
#include "mat_game.h"

#include "graphics/graphics_util.h"



MATArrow::MATArrow() : m_ArrowCount(0)
{
	

	for(int i = 0; i < ARROW_DIR_C; i++)
	{
		m_Sprite[i].Create(ARROW_IMGS[i]);
		m_SpriteSize = m_Sprite[i].m_Size;
		m_Sprite[i].m_Color = ColorfRGBA(1.0f,1.0f,1.0f,0.5f);
	}
}
	
	
void	MATArrow::Render(int StartIndex, float Scale)
{
	for(int i = StartIndex; i < m_ArrowCount; i++)
	{
		m_Sprite[m_RenderList[i].m_Dir].m_Pos = m_RenderList[i].m_Pos;
		m_Sprite[m_RenderList[i].m_Dir].m_Size = m_SpriteSize * Scale; 		
		m_Sprite[m_RenderList[i].m_Dir].RenderRotated();
	}
}

void		MATArrow::Build(const std::vector<MATPathFinding::Tile*>& Path)
{
	m_ArrowCount = 0;
	ARROW_DIR ADir;
	int PathCount =  (int)Path.size();
	for(int i = 1; i < PathCount - 1; i++)
	{
		ADir = GetDir(
								Path[i-1]->m_Y, Path[i-1]->m_X, 
								Path[i]->m_Y, Path[i]->m_X, 
								Path[i+1]->m_Y, Path[i+1]->m_X);

		m_RenderList[m_ArrowCount].m_Dir = ADir;
		m_RenderList[m_ArrowCount].m_Pos = MATGame::GetBoardPos(Path[i]->m_Y, Path[i]->m_X);
		m_ArrowCount++;
	}

	if(PathCount > 1)
	{
		ADir = GetArrowHead(	Path[PathCount-2]->m_Y, Path[PathCount-2]->m_X, 
								Path[PathCount-1]->m_Y, Path[PathCount-1]->m_X);

		m_RenderList[m_ArrowCount].m_Dir = ADir;
		m_RenderList[m_ArrowCount].m_Pos = MATGame::GetBoardPos(Path[PathCount-1]->m_Y, Path[PathCount-1]->m_X);
		m_ArrowCount++;
	}
}

MATArrow::ARROW_DIR		MATArrow::GetDir(int PrevY, int PrevX, int Y,int X, int NextY, int NextX)
{
	if(PrevX == X && X == NextX)
		return ARROW_DIR_TOPTOBOTTOM;

	if(PrevY == Y && Y == NextY)
		return ARROW_DIR_LEFTTORIGHT;

	if( Y == PrevY && X  == PrevX + 1) // to left
	{
		if(  NextY == Y + 1)				// bottom
			return ARROW_DIR_LEFTTOBOTTOM;
		
		if(  NextY == Y - 1)				// top
			return ARROW_DIR_LEFTTOTOP;

	}

	if( PrevY == Y && X == PrevX - 1) // to right
	{
		if(  NextY == Y + 1)
			return ARROW_DIR_RIGHTTOBOTTOM;
		
		if( NextY == Y - 1)
			return ARROW_DIR_RIGHTTOTOP;

	}

	if( X == PrevX  && Y == PrevY + 1) // to top
	{
		if(  X == NextX + 1)
			return ARROW_DIR_LEFTTOTOP;
		
		if(  X == NextX - 1)
			return ARROW_DIR_RIGHTTOTOP;

	}

	if(X == PrevX &&  Y == PrevY - 1) // to bottom
	{
		if(  X == NextX + 1)
			return ARROW_DIR_LEFTTOBOTTOM;
		
		if( X == NextX - 1 )
			return ARROW_DIR_RIGHTTOBOTTOM;

	}
	
	return ARROW_DIR_TORIGHT;
}

MATArrow::ARROW_DIR		MATArrow::GetArrowHead(int Y,int X, int NextY, int NextX)
{
	if(X == NextX && NextY == Y + 1 )
		return ARROW_DIR_TOBOTTOM;

	if(X == NextX && NextY == Y - 1 )
		return ARROW_DIR_TOTOP;

	if(Y == NextY && NextX == X + 1 )
		return ARROW_DIR_TORIGHT;

	if(Y == NextY && NextX == X - 1 )
		return ARROW_DIR_TOLEFT;

	return ARROW_DIR_TOLEFT;
}

void	MATArrow::Clear()
{
	m_ArrowCount = 0;
}

